package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
@RestController
public class CommonController {
    /**
     * 文件上传
     * @param file
     * @return
     * @throws IOException
     */
    @ApiOperation(value = "文件上传")
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) {
        try {
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newName = UUID.randomUUID().toString() + suffix;
            file.transferTo(new File("E:\\java-web-project\\sky-take-out\\images\\" + newName));
            String url="http://localhost:8080/admin/common"+"/download/"+newName;
            log.info("文件上传成功，文件名为：{}", newName);
            return Result.success(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }

    @ApiOperation(value = "文件下载")
    @GetMapping("/download/{fileName}")
    public void downLoad(@PathVariable String fileName, HttpServletResponse response) throws IOException {
        ServletOutputStream os = response.getOutputStream();
        File file=new File("E:\\java-web-project\\sky-take-out\\images\\" + fileName);
        BufferedInputStream bis=new BufferedInputStream(new FileInputStream(file));
        byte[] bytes=new byte[(int)file.length()];
        bis.read(bytes);
        os.write(bytes);
        os.flush();
        os.close();
        bis.close();
    }
}
